﻿using GBH.Models;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace GBH.Controllers
{
    public class UploadController : ApiController
    {
        public async Task<HttpResponseMessage> PostUploadSellOut()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            string pathtemp = "";
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    var fileName = Path.GetFileName(file.Headers.ContentDisposition.FileName.Replace("\"", ""));
                    pathtemp = root + "\\uploads\\Sellout\\" + fileName;

                    if (File.Exists(pathtemp))
                    {
                        File.Delete(pathtemp);
                    }

                    if (!Directory.Exists(root + "\\uploads\\Sellout\\"))
                    {
                        Directory.CreateDirectory(root + "\\uploads\\Sellout\\");
                    }
                    File.Move(file.LocalFileName, pathtemp);

                    using (var ctx = new Models.GBHEntities())
                    {
                        ctx.Database.ExecuteSqlCommand("delete sell_out");

                    }
                    var excel = new Helper.ExcelReader(pathtemp);

                    using (var ctx = new Models.GBHEntities())
                    {
                        var sellOuts = excel.ReadFileToSellOut();
                        ctx.sell_out.AddRange(sellOuts);

                        var fileupload = new FileUploadHistory()
                        {
                            Filename = fileName,
                            FilePath = pathtemp,
                            UploadType = 2,
                            NumberOfRow = sellOuts.Count,
                            DateTime = System.DateTime.Now
                        };

                        ctx.FileUploadHistories.Add(fileupload);
                        ctx.SaveChanges();
                    }


                    //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    //Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
                return Request.CreateResponse(HttpStatusCode.OK, "Import success");
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }

        public async Task<HttpResponseMessage> PostDataStockBalance()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            string pathtemp = "";
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    var fileName = Path.GetFileName(file.Headers.ContentDisposition.FileName.Replace("\"", ""));
                    pathtemp = root + "\\uploads\\Stock\\" + fileName;
                    if (File.Exists(pathtemp))
                    {
                        File.Delete(pathtemp);
                    }

                    if (!Directory.Exists(root + "\\uploads\\Stock\\"))
                    {
                        Directory.CreateDirectory(root + "\\uploads\\Stock\\");
                    }

                    File.Move(file.LocalFileName, pathtemp);
                    using (var ctx = new Models.GBHEntities())
                    {
                        ctx.Database.ExecuteSqlCommand("delete stock");
                    }
                    var excel = new Helper.ExcelReader(pathtemp);
                    using (var ctx = new Models.GBHEntities())
                    {
                        var StockBalances = excel.ReadFileToStockBalance();
                        ctx.stocks.AddRange(StockBalances);

                        var fileupload = new FileUploadHistory()
                        {
                            Filename = fileName,
                            FilePath = pathtemp,
                            UploadType = 1,
                            NumberOfRow = StockBalances.Count,
                            DateTime = System.DateTime.Now
                        };

                        ctx.FileUploadHistories.Add(fileupload);
                        ctx.SaveChanges();
                    }

                    //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    //Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
                return Request.CreateResponse(HttpStatusCode.OK, "Import success");
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }


        public async Task<HttpResponseMessage> PostFileMaterial()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            string pathtemp = "";
            var provider = new MultipartFormDataStreamProvider(root);
            var matProvider = new GBH.Models.Dao.MaterialDao();

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    var fileName = Path.GetFileName(file.Headers.ContentDisposition.FileName.Replace("\"", ""));
                    pathtemp = root + "\\uploads\\FileTemp\\" + fileName;
                    if (File.Exists(pathtemp))
                    {
                        File.Delete(pathtemp);
                    }

                    if (!Directory.Exists(root + "\\uploads\\FileTemp\\"))
                    {
                        Directory.CreateDirectory(root + "\\uploads\\FileTemp\\");
                    }

                    File.Move(file.LocalFileName, pathtemp);

                    var excel = new Helper.ExcelReader(pathtemp);
                    var Mats = excel.ReadFileToMaterialExtension();
                    matProvider.ClearMats();
                    matProvider.SaveMats(Mats);

                    //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    //Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
                return Request.CreateResponse(HttpStatusCode.OK, "Import success");
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }


        public async Task<HttpResponseMessage> PostFileBranch()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            string pathtemp = "";
            var provider = new MultipartFormDataStreamProvider(root);
            var branchProvider = new GBH.Models.Dao.BranchDao();

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    var fileName = Path.GetFileName(file.Headers.ContentDisposition.FileName.Replace("\"", ""));
                    pathtemp = root + "\\uploads\\FileTemp\\" + fileName;
                    if (File.Exists(pathtemp))
                    {
                        File.Delete(pathtemp);
                    }

                    if (!Directory.Exists(root + "\\uploads\\FileTemp\\"))
                    {
                        Directory.CreateDirectory(root + "\\uploads\\FileTemp\\");
                    }

                    File.Move(file.LocalFileName, pathtemp);

                    var excel = new Helper.ExcelReader(pathtemp);
                    var Mats = excel.ReadFileToBranchlExtension();
                    branchProvider.ClearBranch();
                    branchProvider.SaveBranchs(Mats);

                    //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    //Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
                return Request.CreateResponse(HttpStatusCode.OK, "Import success");
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }

        public async Task<HttpResponseMessage> PostFileMatBranch()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            string pathtemp = "";
            var provider = new MultipartFormDataStreamProvider(root);
            var matLocationProvider = new GBH.Models.Dao.MaterialLocationDao();

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    var fileName = Path.GetFileName(file.Headers.ContentDisposition.FileName.Replace("\"", ""));
                    pathtemp = root + "\\uploads\\FileTemp\\" + fileName;
                    if (File.Exists(pathtemp))
                    {
                        File.Delete(pathtemp);
                    }

                    if (!Directory.Exists(root + "\\uploads\\FileTemp\\"))
                    {
                        Directory.CreateDirectory(root + "\\uploads\\FileTemp\\");
                    }

                    File.Move(file.LocalFileName, pathtemp);

                    var excel = new Helper.ExcelReader(pathtemp);
                    var Mats = excel.ReadFileToMatBranch();
                    matLocationProvider.SaveMatLocations(Mats);

                    //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    //Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
                return Request.CreateResponse(HttpStatusCode.OK, "Import success");
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }

        public async Task<HttpResponseMessage> PostFileMinMax()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            string pathtemp = "";
            var provider = new MultipartFormDataStreamProvider(root);
            var minmaxProvider = new GBH.Models.Dao.DaysellMinMaxDao();

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    var fileName = Path.GetFileName(file.Headers.ContentDisposition.FileName.Replace("\"", ""));
                    pathtemp = root + "\\uploads\\FileTemp\\" + fileName;
                    if (File.Exists(pathtemp))
                    {
                        File.Delete(pathtemp);
                    }

                    if (!Directory.Exists(root + "\\uploads\\FileTemp\\"))
                    {
                        Directory.CreateDirectory(root + "\\uploads\\FileTemp\\");
                    }

                    File.Move(file.LocalFileName, pathtemp);

                    var excel = new Helper.ExcelReader(pathtemp);
                    var minmaxs = excel.ReadFileToMinMax();
                    minmaxProvider.SaveSellMinMaxs(minmaxs);

                    //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    //Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
                return Request.CreateResponse(HttpStatusCode.OK, "Import success");
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
    }
}
